package com.flycent.hqhs.http;

import static com.flycent.hqhs.Constants.IP;
import static com.flycent.hqhs.Constants.REST_CONTENT;
import static com.flycent.hqhs.http.WebException.TYPE_SERVER_RETURN_NULL;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.flycent.hqhs.UserBaseInfo;
import com.flycent.hqhs.bean.Brand;
import com.flycent.hqhs.bean.BrandRecommend;
import com.flycent.hqhs.bean.Cart;
import com.flycent.hqhs.bean.Condition;
import com.flycent.hqhs.bean.CouponCode;
import com.flycent.hqhs.bean.Expert;
import com.flycent.hqhs.bean.Logistics;
import com.flycent.hqhs.bean.MainTopAdvertisement;
import com.flycent.hqhs.bean.MyArea;
import com.flycent.hqhs.bean.MyConsigneeAddress;
import com.flycent.hqhs.bean.MyMessage;
import com.flycent.hqhs.bean.MySearchHistory;
import com.flycent.hqhs.bean.OrderDTO;
import com.flycent.hqhs.bean.OrderList;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.PageEntityForSearch;
import com.flycent.hqhs.bean.Product;
import com.flycent.hqhs.bean.ProductCategory;
import com.flycent.hqhs.bean.ProductReviews;
import com.flycent.hqhs.bean.RSAkey;
import com.flycent.hqhs.bean.Reviews;
import com.flycent.hqhs.bean.Search;
import com.flycent.hqhs.bean.UserInfo;
import com.flycent.hqhs.bean.VersionInfo;
import com.flycent.hqhs.util.SdkVersionUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.reflect.TypeToken;

/** 网络请求 */
@SuppressLint("DefaultLocale") 
public class WebClient {

	public static final String TAG = "WebClient";
	public static final String UTF8_FORMAT = "utf-8";

	private Gson gson = new Gson();


	/** Web时间戳 */
	public long getDate() {
		return helper.date;
	}


	/** 2.3	获取RSA加密公钥 */
	public RSAkey publicKey() throws WebException {

		String path = "/common/public_key.jhtml";
		String jsonString = helper.doRequest(IP + path, "GET");

		RSAkey bean = (RSAkey) parse(jsonString, RSAkey.class);

		return bean;
	}

	/** 3.2.1	注册（写法1） */
	public void register(String captchaId, String captcha, String username, String password) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("captchaId", captchaId));
		params.add(new BasicNameValuePair("captcha", captcha));
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));
		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/register" + query;
		helper.doRequest(IP + path, "POST");
	}

	/** 3.2.2	检查用户名是否可用（写法2）  */
	public void checkUsername(String username) throws WebException {
		String query = null;
		try {
			query = String.format("?username=%1$s", URLEncoder.encode(username, UTF8_FORMAT));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/check_username" + query;
		helper.doRequest(IP + path, "GET");
	}

	/** 3.2.3	检查邮箱是否被使用 */
	public void checkEmail(String email) throws WebException {
		String query = null;
		try {
			query = String.format("?email=%1$s", URLEncoder.encode(email, UTF8_FORMAT));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/check_email" + query;
		helper.doRequest(IP + path, "GET");
	}

	/** 3.2.4	检查手机号是否被使用 */
	public void checkMobile(String mobile) throws WebException {
		String query = null;

		query = String.format("?mobile=%1$s", mobile);

		String path = "/rest/member/check_mobile" + query;
		helper.doRequest(IP + path, "GET");
	}

	/** 3.3	验证密码是否正确（需要登录） */
	public void passwordCheck(String password) throws WebException {
		String query = null;
		try {
			query = String.format("?password=%1$s", URLEncoder.encode(password, UTF8_FORMAT));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/password/check" + query;
		helper.doRequest(IP + path, "GET");
	}

	/** 3.4	修改密码（需要登录） */
	public void passwordUpdate(String password, String newPassword) throws WebException {
		String query = null;
		try {
			query = String.format("?password=%1$s&newPassword=%2$s", URLEncoder.encode(password, UTF8_FORMAT), URLEncoder.encode(newPassword, UTF8_FORMAT));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String path = "/rest/member/password/update" + query;
		helper.doRequest(IP + path, "POST");
	}

	/** 3.5.1	找回密码 */
	public void passwordFind(String username, String captchaId, String captcha) throws WebException {
		String query = null;
		try {
			query = String.format("?username=%1$s&captchaId=%2$s&captcha=%3$s", URLEncoder.encode(username, UTF8_FORMAT), captchaId, captcha);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/password/find" + query;
		helper.doRequest(IP + path, "POST");
	}

	/** 3.5.2	重置密码 */
	public void passwordReset(String username, String code, String password) throws WebException {
		String query = null;
		try {
			query = String.format("?username=%1$s&code=%2$s&password=%3$s", URLEncoder.encode(username, UTF8_FORMAT), code, URLEncoder.encode(password, UTF8_FORMAT));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/password/reset" + query;
		helper.doRequest(IP + path, "POST");
	}
	/** 3.5.3找回密码(无图形验证码) */
	public void getCodeWithoutPicture(String username) throws WebException {
		String query = null;
		try {
			query = String.format("?username=%1$s", URLEncoder.encode(username, UTF8_FORMAT));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/password/findWithNoCaptcha" + query;
		helper.doRequest(IP + path, "POST");
	}


	/** 3.6	登录 */
	public UserBaseInfo login(String username, String enPassword) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// params.add(new BasicNameValuePair("captchaId", captchaId));
		// params.add(new BasicNameValuePair("captcha", captcha));
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", enPassword));
		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/login" + query;
		String jsonString = helper.doRequest(IP+path, "POST");

		UserBaseInfo bean = (UserBaseInfo) parse(jsonString, UserBaseInfo.class);

		return bean;
	}

	/** 3.7检查用户是否登录      */
	public void checkLogin() throws WebException{
		String path = "/rest/login/check";
		helper.doRequest(IP+path,"GET");
	}

	/** 3.8 注销 退出登录    */
	public void logout()throws WebException{
		String path = "/rest/logout";
		helper.doRequest(IP+path, "POST");
	}


	/**3.9.0 获取地区 */
	@SuppressWarnings("unchecked")
	@SuppressLint("DefaultLocale") 
	public List<MyArea> area(String id) throws WebException{

		String path = "/common/area.jhtml?parentId="+id;

		String s1 = helper.doRequest(IP+path, "GET");
		List<MyArea> mAreas = new ArrayList<MyArea>();
		try {
			JSONObject jsonObject = new JSONObject(s1);
			Iterator<String> iterator = jsonObject.keys();
			while( iterator.hasNext() ){
				String areaId = iterator.next();
				String areaName = jsonObject.getString(areaId);
				mAreas.add(new MyArea(areaId,areaName));
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return mAreas;
	}


	/** 3.9.2分页获取收货地址 (需要登录)*/
	@SuppressWarnings("unchecked")
	public PageEntity<MyConsigneeAddress> receiver(int pageNumber, int pageSize, String orderProperty, String orderDirection)throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/member/receiver" + query;
		String jsonString = helper.doRequest(IP + path, "GET");
		PageEntity<MyConsigneeAddress> list =  (PageEntity<MyConsigneeAddress>) parse(jsonString, PageEntity.class);
		list.setContent((List<MyConsigneeAddress>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), MyConsigneeAddress.class));

		return list;

	}

	/** 3.9.3新建收货地址  (需要登录)*/
	public void checkNewAddress(String address,String consignee,Boolean isDefault,String phone,String zipCode,String area ) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("address", address));
		params.add(new BasicNameValuePair("consignee", consignee));
		params.add(new BasicNameValuePair("isDefault", isDefault + ""));
		params.add(new BasicNameValuePair("phone", phone));
		params.add(new BasicNameValuePair("zipCode", zipCode));
		params.add(new BasicNameValuePair("area", area));
		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		//		query = String.format("?address=%1$s&consignee=%2$s&isDefault=%3$s&phone=%4$s&zipCode=%5$s&area=%6$s", 
		//				URLEncoder.encode(address, "utf8"),URLEncoder.encode(consignee, "utf8"),isDefault,phone,zipCode,area);
		String path = "/rest/member/receiver"+query;
		helper.doRequest(IP+path, "POST");
	}

	/** 3.9.4修改收货地址  */
	public void modifyAddress(String id,String address,String consignee,Boolean isDefault,String phone,String zipCode,String area )throws WebException{
		String query = null;

		try {
			query = String.format("?address=%1$s&consignee=%2$s&isDefault=%3$s&phone=%4$s&zipCode=%5$s&area=%6$s", 
					URLEncoder.encode(address, UTF8_FORMAT),URLEncoder.encode(consignee, UTF8_FORMAT),isDefault,phone,zipCode,area);
			String path = "/rest/member/receiver/"+id+query;
			helper.doRequest(IP+path, "PUT");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	/** 3.9.5删除收货地址 */
	public void receiverDelete(String id) throws WebException{

		String path = "/rest/member/receiver/" + id;
		helper.doRequest(IP + path, "DELETE");
	}



	/** 3.10.1 关注某个商品 */
	public void favoriteAdd(long id) throws WebException {
		String query = null;

		query = String.format("?id=%1$d", id);

		String path = "/rest/member/favorite/add" + query;
		helper.doRequest(IP + path, "POST");
	}

	/** 3.10.2 查看我的关注列表 */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> favoriteList(int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/favorite/list" + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		PageEntity<Product> list =  (PageEntity<Product>) parse(jsonString, PageEntity.class);
		list.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return list;
	}

	/** 3.10.3 取消某个商品的关注 */
	public void favoriteDelete(long id) throws WebException {
		String query = null;

		query = String.format("?id=%1$d", id);

		String path = "/rest/member/favorite" + query;
		helper.doRequest(IP + path, "DELETE");
	}


	/** 4.2	获取商品列表
	 * @param condition 查询条件，eg:productCategory.id::eq::123
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public PageEntity<Product> products(String condition, int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("q", condition));
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/goods" + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		// 解析分页实体
		PageEntity<Product> bean = (PageEntity) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return bean;
	}

	/** 4.3	获取商品详情 */
	public Product product(String id) throws WebException {

		String path = "/rest/product/" + id;
		String jsonString = helper.doRequest(IP + path, "GET");

		Product bean = (Product) parse(jsonString, Product.class);
		bean.setNowDate(getDate());

		return bean;
	}

	/** 4.4 点击商品 (增加点击量 不需要返回值)*/
	public void doHit(String id ) throws WebException{
		int version = SdkVersionUtil.getAndroidSDKVersion();
		String tool = "android";
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("version", version+""));
		params.add(new BasicNameValuePair("tool", tool + ""));
		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/product/"+id+"/hit"+query;	

		helper.doRequest(IP+path, "POST");
	}


	/** 4.5	获取商品分类 */
	public List<ProductCategory> productCategorys() throws WebException {

		String path = "/rest/product_category";
		String jsonString = helper.doRequest(IP + path, "GET");

		@SuppressWarnings("unchecked")
		List<ProductCategory> list =  (List<ProductCategory>) parse(jsonString, ProductCategory.class);

		return list;
	}

	/** 4.6	获取商品分类详情 */
	public ProductCategory productCategory(String categoryId) throws WebException {

		String path = "/rest/product_category/" + categoryId;
		String jsonString = helper.doRequest(IP + path, "GET");

		ProductCategory bean = (ProductCategory) parse(jsonString, ProductCategory.class);

		return bean;
	}

	/** 4.7	获取品牌 */
	@SuppressWarnings("unchecked")
	public PageEntity<Brand> productBrands(String condition, int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("q", condition));
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/brand" + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		PageEntity<Brand> list =  (PageEntity<Brand>) parse(jsonString, PageEntity.class);
		list.setContent((List<Brand>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Brand.class));

		return list;
	}

	/** 4.8	获取品牌分类详情 */
	public Brand productBrand(String brandId) throws WebException {

		String path = "/rest/brand/" + brandId;
		String jsonString = helper.doRequest(IP + path, "GET");

		Brand bean =  (Brand) parse(jsonString, Brand.class);

		return bean;
	}
	/** 4.10获取商品评论 */
	@SuppressWarnings("unchecked")
	public PageEntity<ProductReviews> getProductReviews(String id) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", 1 + ""));
		params.add(new BasicNameValuePair("pageSize", 20 + ""));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/product/reviews/" + id + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		PageEntity<ProductReviews> list =  (PageEntity<ProductReviews>) parse(jsonString, PageEntity.class);
		list.setContent((List<ProductReviews>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), ProductReviews.class));

		return list;
	}


	/** 4.11根据商品推荐 */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> getRecForProduct(String id) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", 1 + ""));
		params.add(new BasicNameValuePair("pageSize", 100 + ""));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/product/relatedProducts/" + id + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		PageEntity<Product> list =  (PageEntity<Product>) parse(jsonString, PageEntity.class);
		list.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return list;
	}

	/** 5.2	获取关键字提示  修改后 */ 
	public List<MySearchHistory> suggests(String keyword) throws WebException {
		String query = null;
		try {
			query = String.format("?keyword=%1$s", URLEncoder.encode(keyword, UTF8_FORMAT));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String path = "/rest/solr/suggest" + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		@SuppressWarnings("unchecked")
		List<MySearchHistory> list =  (List<MySearchHistory>) parse(jsonString, MySearchHistory.class);

		return list;

	}

	/** 6.2 获取热门搜索  */
	public List<String> getKeyWord() throws WebException{
		String path = "/rest/product/keyWords";

		String jsonString = helper.doRequest(IP+path, "GET");
		List<String> list = null;
		try {
			JSONArray jsonArray = new JSONArray(jsonString);
			Gson gson = new Gson();
			list = gson.fromJson(jsonArray.toString(), 
					new TypeToken<List<String>>(){}.getType());

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return list;
	}

	/** 6.5  获取商品检索条件 */
	@SuppressWarnings("unchecked")
	public List<Condition> condition(String keyword,String category) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("keyword", keyword));
		params.add(new BasicNameValuePair("category", category));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params,UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/solr/product/condition" +query;
		String jsonString = helper.doRequest(IP + path, "GET");

		List<Condition> list =  (List<Condition>) parse(jsonString, Condition.class);

		return list;

	}



	/** 
	 * 6.6  检索商品
	 * 
	 * @param keyword  搜索关键字(required)
	 * @param category  分类(分类名称，分类和关键字至少有一个有值 )
	 * @param page     页码，从1开始计数(optional   default 1)
	 * @param size     一页包含的个数( optional  default 20)
	 * @param sort    排序方式，形如solr_price,-solr_updateDate，表示的是按价格正序时间倒序排列 (optional)
	 * @return
	 * @throws WebException
	 */
	@SuppressWarnings("unchecked")
	public PageEntityForSearch<Search> fuzzy(String p,String keyword,String category,int page,int size,String sort) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("keyword", keyword ));
		params.add(new BasicNameValuePair("category",category));
		params.add(new BasicNameValuePair("page", page+""));
		params.add(new BasicNameValuePair("size", size+""));
		params.add(new BasicNameValuePair("sort", sort));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/solr/product/fuzzy"+query+"&"+p;
		String jsonString = helper.doRequest(IP + path, "GET");

		// 解析分页实体
		@SuppressWarnings({ "rawtypes" })
		PageEntityForSearch<Search> bean = (PageEntityForSearch) parse(jsonString, PageEntityForSearch.class);
		// content赋值
		bean.setContent((List<Search>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Search.class));

		return bean;

	}


	/** 7.4 获取广告位详情 */
	public MainTopAdvertisement adVertisement(String page,String key) throws WebException{
		String query = null;
		try {
			query = String.format("?page=%1$s&key=%2$s", URLEncoder.encode(page, UTF8_FORMAT),key);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String path = "/rest/adPosition"+query;

		String jsonString = helper.doRequest(IP + path, "GET");

		MainTopAdvertisement bean = (MainTopAdvertisement) parse(jsonString, MainTopAdvertisement.class);

		return bean;
	}

	/** 8.2 摇一摇获取商品的 */
	public Product rand() throws WebException{
		String path = "/rest/product/featured_deal/random";
		String jsonString = helper.doRequest(IP + path, "GET");

		Product bean = (Product) parse(jsonString, Product.class);

		return bean;

	}

	/**8.3 获取限时特卖 
	 * 
	 * type 三种类型 {active(当前特卖),history(历史特卖),next(即将特卖)}
	 * */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> active(String type, int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException {
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));


		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/product/featured_deal/"+ type + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		// 解析分页实体
		@SuppressWarnings({ "rawtypes" })
		PageEntity<Product> bean = (PageEntity) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));
		bean.setNowDate(getDate());
		return bean;
	}


	/**  9.2获取购物车详情 */
	public Cart cart() throws WebException{
		String path = "/rest/v2/cart";
		String jsonString = helper.doRequest(IP + path, "GET");

		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;
	}

	/** 9.3添加特卖商品     v2中不包含*/
	public void addSpecialSale(long id,int quantity) throws WebException{
		String query = null;
		query = String.format("?id=%1$s&quantity=%2$s", id,quantity);

		String path = "/rest/cart/addSpecialSale" + query;
		helper.doRequest(IP + path, "POST");

	}

	/** 9.4添加团购商品   v2中不包含*/
	public void addGroupBuy(long id,int quantity) throws WebException{
		String query = null;
		query = String.format("?id=%1$s&quantity=%2$s", id,quantity);

		String path = "/rest/cart/addGroupBuy" + query;
		helper.doRequest(IP + path, "POST");

	}

	/** 9.5 添加普通商品到购物车 */
	public Cart addProduct(long id,int quantity,String promotionType) throws WebException{
		String query = null;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", id + ""));
		params.add(new BasicNameValuePair("quantity", quantity + ""));
		if("".equals(promotionType) || promotionType == null  ){

		}else {
			params.add(new BasicNameValuePair("promotionType", promotionType));
		}

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		//		query = String.format("?id=%1$s&quantity=%2$s&promotionType=%3$s", id,quantity,promotionType);

		String path = "/rest/v2/cart/addProduct" + query;
		String jsonString = helper.doRequest(IP + path, "POST");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;
	}

	/** 9.6添加多个普通商品  */
	public Cart addProducts(long[] ids) throws WebException{
		String query = null;
		StringBuffer buffer =new StringBuffer();
		for (int i = 0; i < ids.length; i++) {
			buffer.append(ids[i]).append(",");
		}
		String value = buffer.substring(0, buffer.length()-1);
		query = String.format("?id=%1$s", value);

		String path = "/rest/v2/cart/addProducts" + query;
		String jsonString = helper.doRequest(IP + path, "POST");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;
	}

	/** 9.7添加组合套餐 */
	public Cart addBundle(long id,int quantity) throws WebException{
		String query = null;
		query = String.format("?id=%1$s&quantity=%2$s", id,quantity);

		String path = "/rest/v2/cart/addProductMeal" + query;
		String jsonString = helper.doRequest(IP + path, "POST");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;

	}

	/** 9.8编辑购物车项的购买数量 */
	public Cart editCart(long id,int quantity) throws WebException{
		String query = null;
		query = String.format("?id=%1$s&quantity=%2$s", id,quantity);

		String path = "/rest/v2/cart/edit" + query;
		String jsonString = helper.doRequest(IP + path, "POST");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;
	}

	/** 9.9选中购物车项  */
	public Cart selectCart(long[] ids) throws WebException{
		String query = null;
		StringBuffer buffer =new StringBuffer();
		for (int i = 0; i < ids.length; i++) {
			buffer.append(ids[i]).append(",");
		}
		String value = buffer.substring(0, buffer.length()-1);
		query = String.format("?ids=%1$s", value);

		String path = "/rest/v2/cart/select" + query;
		String jsonString = helper.doRequest(IP + path, "PUT");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;

	}

	/** 9.10  取消选中购物车项 */
	public Cart unselectCart(long[] ids) throws WebException{
		String query = null;
		StringBuffer buffer =new StringBuffer();
		for (int i = 0; i < ids.length; i++) {
			buffer.append(ids[i]).append(",");
		}
		String value = buffer.substring(0, buffer.length()-1);

		query = String.format("?ids=%1$s", value);

		String path = "/rest/v2/cart/unselect" + query;
		String jsonString = helper.doRequest(IP + path, "PUT");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;

	}

	/** 9.11  删除购物车项  */
	public Cart deleteCart(long id) throws WebException{
		String path = "/rest/v2/cart/";
		String jsonString = helper.doRequest(IP + path+id, "DELETE");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;

	}

	/**  9.12  清空购物车  */
	public Cart clearCart() throws WebException{
		String path = "/rest/v2/cart/clear";
		String jsonString = helper.doRequest(IP + path, "POST");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;
	}



	/**10.1  获取头像image( 需登录) */
	public String getFaceImage() throws WebException{
		String path = "/rest/member/get_image";
		String jsonString =  helper.doRequest(IP+path, "GET");

		return jsonString;
	}

	/**
	 *  10.11 购物车商品数量 
	 * @return
	 * @throws WebException
	 */
	public Cart getCartAllQuantity() throws WebException{
		String path = "/rest/v2/cart/cartProductQuantity";
		String jsonString =  helper.doRequest(IP+path, "GET");
		Cart bean = (Cart) parse(jsonString, Cart.class);
		return bean;

	}


	/** 11.1 获取品牌推荐的八个logo */
	public List<BrandRecommend> getBrand() throws WebException{
		String path = "/rest/home_page/brand";

		String jsonString = helper.doRequest(IP+path, "GET");

		@SuppressWarnings("unchecked")
		List<BrandRecommend> list =  (List<BrandRecommend>) parse(jsonString, BrandRecommend.class);

		return list;

	}




	/** 12 晒单达人 */
	@SuppressWarnings("unchecked")
	public PageEntity<Expert> sunSingle(int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/sunSingle"+query;
		String jsonString = helper.doRequest(IP+path, "GET");
		// 解析分页实体

		PageEntity<Expert> bean = (PageEntity<Expert>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<Expert>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Expert.class));

		return bean;
	}

	/** 12.2首页团购推荐  */
	public List<Product> getGrouponsRecommend(int quantity) throws WebException{
		String query = null;
		query = String.format("?quantity=%1$s", quantity);

		String path = "/rest/home_page/group_buying"+query;
		String jsonString = helper.doRequest(IP+path, "GET");
		@SuppressWarnings("unchecked")
		List<Product> list =  (List<Product>) parse(jsonString, Product.class);
		return list;

	}



	/** 12.3首页猜你喜欢  */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> getRecommend() throws WebException{

		String path = "/rest/home_page/recommend?pageSize=20&pageNumber=1";
		String jsonString = helper.doRequest(IP+path, "GET");

		PageEntity<Product> bean = (PageEntity<Product>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return bean;

	}


	/** 12.4品牌推荐页 */
	@SuppressWarnings("unchecked")
	public PageEntity<BrandRecommend> getBandRecommend(String productCategoryId, int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("productCategoryId", productCategoryId));
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/brand/list"+query;
		String jsonString = helper.doRequest(IP+path, "GET");
		// 解析分页实体

		PageEntity<BrandRecommend> bean = (PageEntity<BrandRecommend>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<BrandRecommend>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), BrandRecommend.class));

		return bean;
	}
	/** 12.5    团购列表 */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> group(int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/product/group_buying/active"+query;
		String jsonString = helper.doRequest(IP+path, "GET");
		// 解析分页实体

		PageEntity<Product> bean = (PageEntity<Product>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));
		bean.setNowDate(getDate());

		return bean;
	}

	/** 12.6品牌跳转页 */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> getBrandList(String brandId , String productCategoryId,int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("brandId", brandId));
		params.add(new BasicNameValuePair("productCategoryId", productCategoryId));
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/brand/products"+query;
		String jsonString = helper.doRequest(IP+path, "GET");
		// 解析分页实体

		PageEntity<Product> bean = (PageEntity<Product>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return bean;
	}


	/** 13.2  提交反馈   */
	public void submit(String contact,String content) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("contact", contact));
		params.add(new BasicNameValuePair("content", content));
		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/feedback/submit"+query;
		helper.doRequest(IP+path, "POST");
	}
	/** 15.1获取支付方式 */



	/**  15.2查询配送方式 */
	public List<Logistics> deliveryPrice(long areaId,int weight,String payPrice) throws WebException{
		String query = null;
		query = String.format("?areaId=%1$s&weight=%2$s&payPrice=%3$s", areaId,weight,payPrice);

		String path = "/rest/member/order/deliveryPrice" + query;
		String jsonString = helper.doRequest(IP + path, "GET");

		@SuppressWarnings("unchecked")
		List<Logistics> list =  (List<Logistics>) parse(jsonString, Logistics.class);

		return list;

	}
	/**
	 * 15.3 立即购买                                                                          必须     
	 * 
	 * @param itemId  skuId                 是
	 * @param quantity    数量                                               是
	 * @param receiverId  收货地址id             是
	 * @param paymentMethodId   支付方式Id       是
	 * @param deliveryCorpId    物流公司Id       否    
	 * @param code    优惠券码                                                   否
	 * @param isInvoice   是否开具发票                                 否
	 * @param invoiceTitle   发票抬头                                 否
	 * @param useBalance   是否使用余额                               否
	 * @return
	 * @throws WebException
	 */
	public OrderList buyNow(long itemId,int quantity,long receiverId,String paymentMethodId,
			String deliveryCorpId,String code,boolean isInvoice,String invoiceTitle,boolean useBalance,String promotionType) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("itemId", itemId+""));
		params.add(new BasicNameValuePair("quantity", quantity+""));
		params.add(new BasicNameValuePair("receiverId", receiverId+""));
		params.add(new BasicNameValuePair("paymentMethodId", paymentMethodId+""));
		params.add(new BasicNameValuePair("deliveryCorpId", deliveryCorpId+""));
		params.add(new BasicNameValuePair("code", code));
		params.add(new BasicNameValuePair("isInvoice", isInvoice+""));
		params.add(new BasicNameValuePair("invoiceTitle", invoiceTitle));
		params.add(new BasicNameValuePair("useBalance", useBalance+""));
		if("".equals(promotionType) || promotionType == null  ){
		}else {
			params.add(new BasicNameValuePair("promotionType", promotionType+""));
		}

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/member/order/buyNow"+query;
		String jsonString = helper.doRequest(IP+path, "POST");
		OrderList bean = (OrderList) parse(jsonString, OrderList.class);
		return bean;
	}

	/**
	 * 15.4购物车提交购买                                                                  必须     
	 * 
	 * @param cartToken  购物车token            是
	 * @param receiverId  收货地址id             是
	 * @param paymentMethodId   支付方式Id       是
	 * @param deliveryCorpId    物流公司Id       否   
	 * @param code    优惠券码                                                  否
	 * @param isInvoice   是否开具发票                                否
	 * @param invoiceTitle   发票抬头                                否
	 * @param useBalance   是否使用余额                              否
	 * @return
	 * @throws WebException
	 */
	public OrderList buyCart(String cartToken,long receiverId,String paymentMethodId,
			String deliveryCorpId,String code,boolean isInvoice,String invoiceTitle,boolean useBalance) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("cartToken", cartToken+""));
		params.add(new BasicNameValuePair("receiverId", receiverId+""));
		params.add(new BasicNameValuePair("paymentMethodId", paymentMethodId+""));
		params.add(new BasicNameValuePair("deliveryCorpId", deliveryCorpId+""));
		params.add(new BasicNameValuePair("code", code));
		params.add(new BasicNameValuePair("isInvoice", isInvoice+""));
		params.add(new BasicNameValuePair("invoiceTitle", invoiceTitle));
		params.add(new BasicNameValuePair("useBalance", useBalance+""));
		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/member/order/create"+query;
		String jsonString = helper.doRequest(IP+path, "POST");
		OrderList bean = (OrderList) parse(jsonString, OrderList.class);
		return bean;
	}
	/**  进入到订单流程 */
	public OrderDTO doGetPayment(String sn) throws WebException{
		String path = "/rest/member/order/payment/";
		String jsonString = helper.doRequest(IP+path+sn, "GET");
		OrderDTO bean = (OrderDTO)parse(jsonString, OrderDTO.class);

		return bean;

	}


	/** 15.6购买使用优惠券 */
	@SuppressWarnings("unchecked")
	public  List<CouponCode> getCanUseCouponList(boolean isCart,String productId,String quantity) throws WebException{
		String query = null;
		if(isCart){
			query = String.format("?isCart=%1$s", isCart);
		}else {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("isCart", isCart+""));
			params.add(new BasicNameValuePair("productId", productId));
			params.add(new BasicNameValuePair("quantity", quantity + ""));

			HttpEntity reqEntity = null;
			try {
				reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
				query = "?" + EntityUtils.toString(reqEntity);
			} catch (ParseException | IOException e) {
				e.printStackTrace();
			}
		}
		String path = "/rest/member/order/getCouponCodes"+query;
		String jsonString = helper.doRequest(IP+path, "GET");
		List<CouponCode> list =  (List<CouponCode>) parse(jsonString, CouponCode.class);
		return list;
	}
	/** 15.7获取支付状态 */



	/** 账户基本信息 */
	public UserInfo getinfo() throws WebException{
		String path = "/rest/member/info";
		String jsonString = helper.doRequest(IP+path, "GET"); 

		UserInfo bean = (UserInfo) parse(jsonString, UserInfo.class);

		return bean;
	} 
	/**16.2  获取订单列表 */
	@SuppressWarnings("unchecked")
	public PageEntity<OrderList> getOrderList(String orderStatus,int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		//			params.add(new BasicNameValuePair("orderStatus", orderStatus));
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/order/myOrder"+query+"&orderStatus="+orderStatus;
		String jsonString = helper.doRequest(IP+path, "GET");

		// 解析分页实体

		PageEntity<OrderList> bean = (PageEntity<OrderList>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<OrderList>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), OrderList.class));

		return bean;

	}
	/**16.3  获取订单详情 */
	public OrderList getOrderDetail(String id) throws WebException{
		String path = "/rest/member/order/";
		String jsonString = helper.doRequest(IP+path+id, "GET");

		OrderList bean = (OrderList) parse(jsonString, OrderList.class);

		return bean;

	}
	
	/** 16.3.1  订单签收 */
	public OrderList SignOrder(String sn) throws WebException{
		String path = "/rest/member/order/signIn/"+sn;
		
		String jsonString = helper.doRequest(IP+path, "GET");
		
		OrderList bean = (OrderList) parse(jsonString, OrderList.class);
		
		return bean;		
		
	}
	
	
	
	
	/** 16.4  我的优惠券 */
	@SuppressWarnings("unchecked")
	public PageEntity<CouponCode> getCouponList(String status,int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("status", status));
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/coupon/list"+query;
		String jsonString = helper.doRequest(IP+path, "GET");

		// 解析分页实体

		PageEntity<CouponCode> bean = (PageEntity<CouponCode>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<CouponCode>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), CouponCode.class));

		return bean;

	}

	/**
	 * 16.5评价
	 * @param productId
	 * @param orderItemChildId
	 * @param score
	 * @param content
	 * @throws WebException
	 */
	public void doReviews(long orderItemChildId,String score,String content)throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("orderItemChildId", orderItemChildId + ""));
		params.add(new BasicNameValuePair("score", score + ""));
		params.add(new BasicNameValuePair("content", content));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/reviews/review"+query;
		helper.doRequest(IP+path, "POST");

	}

	/** 16.7我的消息 */
	@SuppressWarnings("unchecked")
	public PageEntity<MyMessage> getMessageList(int pageNumber, int pageSize, String orderProperty, String orderDirection) throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}

		String path = "/rest/member/message/list"+query;
		String jsonString = helper.doRequest(IP+path, "GET");

		// 解析分页实体
		PageEntity<MyMessage> bean = (PageEntity<MyMessage>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<MyMessage>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), MyMessage.class));

		return bean;

	}

	/**  未读消息个数 */
	public MyMessage getNoReadMessage()throws WebException{
		String path = "/rest/member/message/getNumber";
		String jsonString = helper.doRequest(IP+path, "GET");
		MyMessage bean = (MyMessage) parse(jsonString, MyMessage.class);
		return bean;

	}


	/** 16.8点击消息  */
	@SuppressWarnings("unchecked")
	public  PageEntity<MyMessage> doHitMessage(long id) throws WebException{
		String path = "/rest/member/message/hit/";
		String  jsonString = helper.doRequest(IP+path+id, "POST");

		// 解析分页实体
		PageEntity<MyMessage> bean = (PageEntity<MyMessage>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<MyMessage>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), MyMessage.class));

		return bean;
	}

	/** 16.9 删除消息 */
	@SuppressWarnings("unchecked")
	public  PageEntity<MyMessage> deleteMessage(long id) throws WebException{
		String path = "/rest/member/message/delete/";
		String  jsonString = helper.doRequest(IP+path+id, "POST");

		// 解析分页实体
		PageEntity<MyMessage> bean = (PageEntity<MyMessage>) parse(jsonString, PageEntity.class);
		// content赋值
		bean.setContent((List<MyMessage>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), MyMessage.class));

		return bean;
	}


	/** 16.10可晒单/评价列表 */
	@SuppressWarnings("unchecked")
	public PageEntity<Reviews> getReviewsList(int pageNumber, int pageSize, String orderProperty, String orderDirection)throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/reviews/list" + query;
		String jsonString = helper.doRequest(IP + path, "GET");
		PageEntity<Reviews> list =  (PageEntity<Reviews>) parse(jsonString, PageEntity.class);
		list.setContent((List<Reviews>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Reviews.class));

		return list;

	}
	/** 16.11我的浏览记录 */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> getBrowseList(int pageNumber, int pageSize, String orderProperty, String orderDirection)throws WebException{
		String query = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("pageNumber", pageNumber + ""));
		params.add(new BasicNameValuePair("pageSize", pageSize + ""));
		params.add(new BasicNameValuePair("orderProperty", orderProperty));
		params.add(new BasicNameValuePair("orderDirection", orderDirection));

		HttpEntity reqEntity = null;
		try {
			reqEntity = new UrlEncodedFormEntity(params, UTF8_FORMAT);
			query = "?" + EntityUtils.toString(reqEntity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		String path = "/rest/member/browse/list" + query;
		String jsonString = helper.doRequest(IP + path, "GET");
		PageEntity<Product> list =  (PageEntity<Product>) parse(jsonString, PageEntity.class);
		list.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return list;

	}
	/** 16.12删除历史浏览记录 */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> deleteBrowse(long id) throws WebException{
		String path = "/rest/member/browse/delete/";

		String jsonString = helper.doRequest(IP+path+id, "POST");
		PageEntity<Product> list =  (PageEntity<Product>) parse(jsonString, PageEntity.class);
		list.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return list;

	}
	/** 16.13删除所有浏览记录  */
	@SuppressWarnings("unchecked")
	public PageEntity<Product> deleteAllBrowse() throws WebException{
		String path = "/rest/member/browse/deleteAll";

		String jsonString = helper.doRequest(IP+path, "POST");
		PageEntity<Product> list =  (PageEntity<Product>) parse(jsonString, PageEntity.class);
		list.setContent((List<Product>) parse(new JsonParser().parse(jsonString).getAsJsonObject().get(REST_CONTENT).toString(), Product.class));

		return list;

	}
	/**  检查更新  */
	public VersionInfo getVersion() throws WebException{
		String path = "/rest/versionInfo/current";
		String jsonString = helper.doRequest(IP+path, "GET");

		VersionInfo bean =  (VersionInfo) parse(jsonString, VersionInfo.class);
		return bean;
	}




	// -------------------------------------------------------

	/**
	 * 解析web返回的json
	 * @param jsonString
	 * @param clazz 无返回值，传null
	 * @return
	 * @throws WebException
	 */
	private <T> Object parse(String jsonString, Class<T> clazz) throws WebException {
		JsonElement element = new JsonParser().parse(jsonString);

		if (!element.isJsonNull()) { 											// "content":null情况
			if (element.isJsonArray() && element.getAsJsonArray().size() == 0) 	// "content":[]情况
				throw new WebException(context, TYPE_SERVER_RETURN_NULL);
			else if (element.isJsonArray()) { 		// content是【JsonArray】
				List<T> list = new ArrayList<>();

				JsonArray arr = element.getAsJsonArray();
				for (int i = 0; i < arr.size(); i ++) {
					JsonElement j = arr.get(i);
					T t = gson.fromJson(j, clazz);
					list.add(t);
				}
				return list;						// Result

			} else if (element.isJsonObject()) {	// content是【JsonObject】
				T t = gson.fromJson(element, clazz);
				return t; 							// Result
			} else 									// content是【JsonPrimitive】
				return 								// Result
						clazz == BigDecimal.class ? element.getAsBigDecimal() :
							clazz == BigInteger.class ? element.getAsBigInteger() :
								clazz == Boolean.class ? element.getAsBoolean() :
									clazz == Byte.class ? element.getAsByte() :
										clazz == Character.class ? element.getAsCharacter() :
											clazz == Double.class ? element.getAsDouble() :
												clazz == Float.class ? element.getAsFloat() :
													clazz == Integer.class ? element.getAsInt() :
														clazz == JsonArray.class ? element.getAsJsonArray() :
															clazz == JsonNull.class ? element.getAsJsonNull() :
																clazz == JsonObject.class ? element.getAsJsonObject() :
																	clazz == JsonPrimitive.class ? element.getAsJsonPrimitive() :
																		clazz == Long.class ? element.getAsLong() :
																			clazz == Number.class ? element.getAsNumber() :
																				clazz == Short.class ? element.getAsShort() :
																					clazz == String.class ? element.getAsString() :
																						element; 
		} else
			throw new WebException(context, TYPE_SERVER_RETURN_NULL);
	}

	// --------------------------------------------------------------------
	private static WebClient instance = null;

	private Context context = null;
	private WebHelper helper = null;

	private WebClient(Context context) {
		super();
		this.context = context;
		this.helper = WebHelper.getInstance(context);
	}


	/** get WebClient */
	public static WebClient getInstance(Context context) {
		if (null == instance)
			instance = new WebClient(context);
		return instance;
	}
}